<?php
defined('IN_PHPCMS') or exit('No permission resources.');
pc_base::load_app_class('admin', 'admin', 0);
pc_base::load_sys_class('form', '', 0);
set_time_limit(300);
class gmap extends admin
{
    protected $db;
    public function __construct()
    {
        parent::__construct();
        $this->siteid = $this->get_siteid();
        $this->categorys = getcache('category_content_'.$this->siteid, 'commons');
        $models=getcache('model', 'commons');
        $this->model_tables=array();
        foreach ($models as $model) {
            if ($model['disabled']=='1') {
                continue;
            }
            $this->model_tables[]='phpcms_'.$model["tablename"];
        }
    }

    public function query($sql)
    {
        if (!isset($this->db)) {
            $this->db = pc_base::load_model('content_model');
        }
        return $this->db->fetch_array($this->db->query($sql));
    }

    public function getOne($sql)
    {
        $a = $this->query($sql);
        if (sizeof($a)==0) {
            return null;
        }
        return $a[0];
    }

    public function create_folders($dir)
    {
        return is_dir($dir) or ($this->create_folders(dirname($dir)) and mkdir($dir, 0777));
    }


    public function buildSitemap($y, $m, $root)
    {
        $this->create_folders($root."sitemaps/$y");
        $where = " inputtime>=".mktime(0, 0, 0, $m, 1, $y)." AND status=99 AND inputtime<".mktime(0, 0, 0, ($m%12)+1, 1, $y+floor($m/12));
        $sql=" SELECT * FROM ( ";
        foreach ($this->model_tables as $table) {
            $sql =$sql." SELECT DATE_FORMAT(FROM_UNIXTIME(updatetime),'%Y-%m-%d') AS modify,url,inputtime FROM $table WHERE $where";

            if ($table!=end($this->model_tables)) {
                $sql=$sql." UNION ALL ";
            } else {
                $sql= $sql." ) AS tab ORDER BY modify DESC";
            }
        }
        $urlset=array();
        if (!empty($this->model_tables)) {
            $urlset = $this->query($sql);
        }

        $xml = array('<?xml version="1.0" encoding="UTF-8"?>', '<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">' );
        foreach ($urlset as $u) {
            // if (strpos($u["url"], '://')===false) {
            //     $u["url"] = 'http:'.$u["url"];
            // }
            if (strpos($u["url"], '/')===0) {
                $u["url"] = rtrim(APP_PATH, '/').$u["url"];
            }
            $xml []= implode("", array(
                  "<url>",
                  "<loc>", $u["url"], "</loc>",
                  "<lastmod>", $u["modify"], "</lastmod>",
                  "<changefreq>daily</changefreq>",
                  "<priority>0.7</priority>",
                  "</url>"
              ));
        }
        $xml []= '</urlset>';
        $xml = implode("\r\n", $xml);
        file_put_contents($root."sitemaps/$y/$m.xml", $xml);
    }

    public function buildIndex($fileList, $domain, $root)
    {
        $domain=trim($domain, '/');
        // $newdomain = $domain;
        // if (strpos($domain, '://')===false) {
        //     $domain = 'http:'.$domain;
        // }
        // var_dump($domain);
        // exit();
        $obj = array();
        foreach ($fileList as $item) {
            $obj[ $item["y"].intval($item["m"], 10) ] = implode("", array(
                  "<sitemap>",
                  "<loc>$domain/sitemaps/".$item["y"]."/".$item["m"].".xml</loc>",
                  "<lastmod>".date("Y-m-d")."</lastmod>",
                  "</sitemap>"
              ));
        }
        $xml = file_get_contents($root."sitemaps.xml");
        $matches = array();
        $mCount = preg_match_all(
            '/<sitemap>\s*<loc>\s*http:\/\/[^\/]+\/sitemaps\/(\d+)\/(\d+)\.xml\s*<\/loc>\s*<lastmod>[^<]*<\/lastmod>\s*<\/sitemap>/i',
            $xml,
            $matches
        );
        $newXML = array(
              '<?xml version="1.0" encoding="UTF-8"?><sitemapindex xmlns="http://www.google.com/schemas/sitemap/0.9">'
          );
        foreach ($obj as $key=>$value) {
            $newXML []= $value;
        }
        for ($i=0;$i<$mCount;$i++) {
            $key = $matches[1][$i].intval($matches[2][$i], 10);
            if (isset($obj[$key])) {
                // $newXML []= $obj[$key];
                  // unset($obj[$key]);
            } else {
                $newXML []= $matches[0][$i];
            }
        }
        //print_r( $obj );
        $newXML []= '</sitemapindex>';
        $newXML = implode("\r\n", $newXML);
        file_put_contents($root."sitemaps.xml", $newXML);



        //---https----
    }


    public function build()
    {
        // $lastMdf['timestamp'] ='1546272000';
        //读站点缓存
        //根据当前站点,取得文件存放路径
        $systemconfig = pc_base::load_config('system');
        $html_root = substr($systemconfig['html_root'], 1);
        $dir = PHPCMS_PATH.$html_root.DIRECTORY_SEPARATOR;
        $this_domain =APP_PATH;
        if (!isset($_GET['page'])) {
            $fileList=array();
            //没传分页参数，代表第一次生成，需要生成所有要生成地图的年月日存缓存
            $siteid = $this->siteid;
            $sitecache = getcache('sitelist', 'commons');
            //判断当前站点目录,是PHPCMS则把文件写到根目录下, 不是则写到分站目录下.(分站目录用由静态文件路经html_root和分站目录dirname组成)
            // if ($siteid==1) {

            // } else {
            // $dir = PHPCMS_PATH.$html_root.DIRECTORY_SEPARATOR.$sitecache[$siteid]['dirname'].DIRECTORY_SEPARATOR;
            // }
            $page = isset($_GET['page']) && intval($_GET['page']) ? intval($_GET['page']):1;
            $pagesize=intval(trim($_GET['pagesize'])) && intval($_GET['pagesize']) ? intval($_GET['pagesize']):10;
            $offset = $pagesize*($page-1);
            //模型缓存
            // $modelcache = getcache('model','commons');
            //获取当前站点域名,下面生成URL时会用到.

            // $models=getcache('model', 'commons');

            // $model_tables=array();
            // foreach ($models as $model) {
            //     if ($model['disabled']=='1') {
            //         continue;
            //     }
            //     $model_tables[]='phpcms_'.$model["tablename"];
            // }
            if (!empty($this->model_tables)) {
                $sql=" SELECT year(input) AS y, month(input) AS m FROM  ( ";
            }
            foreach ($this->model_tables as $table) {
                $sql =$sql." SELECT from_unixtime(inputtime) AS input, updatetime FROM $table WHERE status=99 ";

                if ($table!=end($this->model_tables)) {
                    $sql=$sql." UNION ALL ";
                } else {
                    $sql= $sql." ) AS tab GROUP BY y, m ORDER BY MAX(updatetime) DESC";
                }
            }

            if (!empty($this->model_tables)) {
                $fileList = $this->query($sql);
                setcache('pc_sitemap_data', $fileList);
            }
        } else {
            $fileList=getcache('pc_sitemap_data');
            $page = isset($_GET['page']) && intval($_GET['page']) ? intval($_GET['page']):1;
            $pagesize=intval(trim($_GET['pagesize'])) && intval($_GET['pagesize']) ? intval($_GET['pagesize']):10;
        }

        // $countsql = implode(" ", array(
        //     "SELECT year(input) AS y, month(input) AS m FROM (",
        //     "SELECT from_unixtime(inputtime) AS input, updatetime FROM phpcms_news WHERE status=99 AND catid=58 AND updatetime >", $lastMdf['timestamp'],
        //         "UNION ALL",
        //     "SELECT from_unixtime(inputtime) AS input, updatetime FROM phpcms_novel WHERE status=99 AND updatetime >", $lastMdf['timestamp'],
        //     ") AS tab GROUP BY y, m ORDER BY MAX(updatetime) DESC"
        // ));
        // $counts = $this->query($countsql);
        // $mytotal=count($counts);
        // $endtotal=ceil($mytotal/$pagesize);

        // if ($page<=$endtotal) {
        // foreach ($fileList as $item) {
        if (isset($fileList[$page-1])) {
            $item=$fileList[$page-1];
            $count=count($fileList);
            $endtotal=ceil($count/$pagesize);
            $this->buildSitemap($item['y'], $item['m'], $dir);
            $nextpage=$page+1;
            showmessage('正在生成电脑版地图第'.$page.'页/共'.$endtotal.'页', "?m=admin&c=gmap&a=build&page=$nextpage&count=$count");
        } else {
            $this->buildIndex($fileList, $this_domain, $dir);
            showmessage('电脑版地图生成完成!继续生成手机地图...', "?m=admin&c=gmap&a=public_sj_build", 5000);
        }
    }


    /**
     *
     * Enter 生成google sitemap, 百度新闻协议
     */
    public function set()
    {
        include $this->admin_tpl('gmap');
    }

    /************************************生成手机版百度sitemap地图索引*********************************************************/

    public function public_sj_build()
    {
        //读站点缓存
        // $html_root = substr($systemconfig['html_root'], 1);
        $html_root= pc_base::load_config('system', 'html_mobile_root');
        $dir = PHPCMS_PATH.$html_root.DIRECTORY_SEPARATOR;
        $this_domain =APP_MOBILE_PATH;
        if (!isset($_GET['page'])) {
            $fileList=array();
            //没传分页参数，代表第一次生成，需要生成所有要生成地图的年月日存缓存
            $siteid = $this->siteid;
            $sitecache = getcache('sitelist', 'commons');

            //根据当前站点,取得文件存放路径
            $systemconfig = pc_base::load_config('system');
            //判断当前站点目录,是PHPCMS则把文件写到根目录下, 不是则写到分站目录下.(分站目录用由静态文件路经html_root和分站目录dirname组成)
            // if ($siteid==1) {

            // } else {
            // $dir = PHPCMS_PATH.$html_root.DIRECTORY_SEPARATOR.$sitecache[$siteid]['dirname'].DIRECTORY_SEPARATOR;
            // }
            $page = isset($_GET['page']) && intval($_GET['page']) ? intval($_GET['page']):1;
            $pagesize=intval(trim($_GET['pagesize'])) && intval($_GET['pagesize']) ? intval($_GET['pagesize']):10;
            $offset = $pagesize*($page-1);
            //模型缓存
            // $modelcache = getcache('model','commons');
            //获取当前站点域名,下面生成URL时会用到.
            // $this_domain = substr($sitecache[$siteid]['domain'], 0, strlen($sitecache[$siteid]['domain'])-1);
            // $models=getcache('model', 'commons');

            // $model_tables=array();
            // foreach ($models as $model) {
            //     if ($model['disabled']=='1') {
            //         continue;
            //     }
            //     $model_tables[]='phpcms_'.$model["tablename"];
            // }
            if (!empty($this->model_tables)) {
                $sql=" SELECT year(input) AS y, month(input) AS m FROM  ( ";
            }
            foreach ($this->model_tables as $table) {
                $sql =$sql." SELECT from_unixtime(inputtime) AS input, updatetime FROM $table WHERE status=99 ";

                if ($table!=end($this->model_tables)) {
                    $sql=$sql." UNION ALL ";
                } else {
                    $sql= $sql." ) AS tab GROUP BY y, m ORDER BY MAX(updatetime) DESC";
                }
            }

            if (!empty($this->model_tables)) {
                $fileList = $this->query($sql);
                setcache('mobile_sitemap_data', $fileList);
            }
        } else {
            $fileList=getcache('mobile_sitemap_data');
            $page = isset($_GET['page']) && intval($_GET['page']) ? intval($_GET['page']):1;
            $pagesize=intval(trim($_GET['pagesize'])) && intval($_GET['pagesize']) ? intval($_GET['pagesize']):10;
        }
        if (isset($fileList[$page-1])) {
            $item=$fileList[$page-1];
            $count=count($fileList);
            $endtotal=ceil($count/$pagesize);
            $this->sj_buildSitemap($item['y'], $item['m'], $dir);
            $nextpage=$page+1;
            showmessage('正在生成手机版地图第'.$page.'页/共'.$endtotal.'页', "?m=admin&c=gmap&a=public_sj_build&page=$nextpage&count=$count");
        } else {
            $this->sj_buildIndex($fileList, $this_domain, $dir);

            showmessage('全部生成完毕', "?m=admin&c=gmap&a=set");
        }
    }

    public function sj_buildSitemap($y, $m, $root)
    {
        $this->create_folders($root."sitemaps/$y");
        $where = " inputtime>=".mktime(0, 0, 0, $m, 1, $y)." AND status=99 AND inputtime<".mktime(0, 0, 0, ($m%12)+1, 1, $y+floor($m/12));
        $sql=" SELECT * FROM ( ";
        foreach ($this->model_tables as $table) {
            $sql =$sql." SELECT DATE_FORMAT(FROM_UNIXTIME(updatetime),'%Y-%m-%d') AS modify,url,inputtime FROM $table WHERE $where";

            if ($table!=end($this->model_tables)) {
                $sql=$sql." UNION ALL ";
            } else {
                $sql= $sql." ) AS tab ORDER BY modify DESC";
            }
        }
        $urlset=array();
        if (!empty($this->model_tables)) {
            $urlset = $this->query($sql);
        }

        $xml = array('<?xml version="1.0" encoding="UTF-8"?>', '<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">' );
        foreach ($urlset as $u) {
            // if (strpos($u["url"], '://')===false) {
            //     $u["url"] = 'http:'.$u["url"];
            // }
            if (strpos($u["url"], '/')===0) {
                $u["url"] = rtrim(APP_MOBILE_PATH, '/').$u["url"];
            }
            $xml []= implode("", array(
                "<url>",
                "<loc>", $u["url"], "</loc>",
                "<lastmod>", $u["modify"], "</lastmod>",
                "<changefreq>daily</changefreq>",
                "<priority>0.7</priority>",
                "</url>"
            ));
        }
        $xml []= '</urlset>';
        $xml = implode("\r\n", $xml);
        file_put_contents($root."sitemaps/$y/$m.xml", $xml);
    }

    public function sj_buildIndex($fileList, $domain, $root)
    {
        // $newdomain=$domain;
        // if (strpos($domain, '://')===false) {
        //     $domain = 'http:'.$domain;
        // }
        $domain=ltrim($domain, '/');
        $obj = array();
        foreach ($fileList as $item) {
            $obj[ $item["y"].intval($item["m"], 10) ] = implode("", array(
                "<sitemap>",
                "<loc>".$domain."sitemaps/".$item["y"]."/".$item["m"].".xml</loc>",
                "<lastmod>".date("Y-m-d")."</lastmod>",
                "</sitemap>"
            ));
        }
        $xml = file_get_contents($root."sitemaps.xml");
        $matches = array();
        $mCount = preg_match_all(
            '/<sitemap>\s*<loc>\s*http:\/\/[^\/]+\/sitemaps\/(\d+)\/(\d+)\.xml\s*<\/loc>\s*<lastmod>[^<]*<\/lastmod>\s*<\/sitemap>/i',
            $xml,
            $matches
        );
        $newXML = array(
            '<?xml version="1.0" encoding="UTF-8"?><sitemapindex xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">'
        );
        foreach ($obj as $key=>$value) {
            $newXML []= $value;
        }
        for ($i=0;$i<$mCount;$i++) {
            $key = $matches[1][$i].intval($matches[2][$i], 10);
            if (isset($obj[$key])) {
                // $newXML []= $obj[$key];
                // unset($obj[$key]);
            } else {
                $newXML []= $matches[0][$i];
            }
        }
        $newXML []= '</sitemapindex>';
        $newXML = implode("\r\n", $newXML);
        file_put_contents($root."sitemaps.xml", $newXML);
    }


    /************************************生成mip版百度sitemap地图索引*********************************************************/

    public function public_mip_build()
    {
        $lastMdf['timestamp'] ='946656000';
        //读站点缓存
        $siteid = $this->siteid;
        $sitecache = getcache('sitelist', 'commons');

        //根据当前站点,取得文件存放路径
        $systemconfig = pc_base::load_config('system');
        $html_root = substr($systemconfig['html_root'], 1);
        //判断当前站点目录,是PHPCMS则把文件写到根目录下, 不是则写到分站目录下.(分站目录用由静态文件路经html_root和分站目录dirname组成)
        $dir = PHPCMS_PATH.'mip'.DIRECTORY_SEPARATOR;
        $page = isset($_GET['page']) && intval($_GET['page']) ? intval($_GET['page']):1;
        $pagesize=intval(trim($_GET['pagesize'])) && intval($_GET['pagesize']) ? intval($_GET['pagesize']):10;
        $offset = $pagesize*($page-1);
        //获取当前站点域名,下面生成URL时会用到.
        $this_domain = siteurl(3).'/';
        $sql = implode(" ", array(
            "SELECT year(input) AS y, month(input) AS m FROM (",
            "SELECT from_unixtime(inputtime) AS input, updatetime FROM phpcms_download WHERE status=99 and updatetime >", $lastMdf['timestamp'],
            //	"UNION ALL",
            //"SELECT from_unixtime(inputtime) AS input, updatetime FROM phpcms_news WHERE status=99 and updatetime >", $lastMdf['timestamp'],
            //	"UNION ALL",
            //"SELECT from_unixtime(inputtime) AS input, updatetime FROM phpcms_picture WHERE status=99 and updatetime >", $lastMdf['timestamp'],
            ") AS tab GROUP BY y, m ORDER BY MAX(updatetime) DESC limit $offset,$pagesize"
        ));
        $fileList = $this->query($sql);
        $countsql = implode(" ", array(
            "SELECT year(input) AS y, month(input) AS m FROM (",
            "SELECT from_unixtime(inputtime) AS input, updatetime FROM phpcms_download WHERE status=99 and updatetime >", $lastMdf['timestamp'],
            //"UNION ALL",
            //"SELECT from_unixtime(inputtime) AS input, updatetime FROM phpcms_news WHERE status=99 and updatetime >", $lastMdf['timestamp'],
            //"UNION ALL",
            //"SELECT from_unixtime(inputtime) AS input, updatetime FROM phpcms_picture WHERE status=99 and updatetime >", $lastMdf['timestamp'],
            ") AS tab GROUP BY y, m ORDER BY MAX(updatetime) DESC"
        ));
        $counts = $this->query($countsql);
        $mytotal=count($counts);
        $endtotal=ceil($mytotal/$pagesize);
        if ($page<=$endtotal) {
            foreach ($fileList as $item) {
                $this->mip_buildSitemap($item['y'], $item['m'], $dir);
            }
            $page++;
            showmessage('正在生成mip版sitemap地图第'.$page.'页/共'.$endtotal.'页', "?m=admin&c=gmap&a=public_mip_build&page=".$page);
        }
        $this->mip_buildIndex($counts, $this_domain, $dir);
        showmessage('全部地图生成完成', "?m=admin&c=gmap&a=set");
    }

    public function mip_buildSitemap($y, $m, $root)
    {
        $this->create_folders($root."sitemaps/$y");
        $where = "inputtime>=".mktime(0, 0, 0, $m, 1, $y)." AND url !='' AND islink=0 "." AND status=99 and inputtime<".mktime(0, 0, 0, ($m%12)+1, 1, $y+floor($m/12));
        $sql = array(
            "SELECT * FROM (",
            "SELECT DATE_FORMAT(FROM_UNIXTIME(updatetime),'%Y-%m-%d') AS modify, url, inputtime FROM phpcms_download WHERE ", $where,
            ") AS tab ORDER BY modify desc"
        );
        $sql = implode(" ", $sql);
        $urlset = $this->query($sql);
        $xml = array('<?xml version="1.0" encoding="UTF-8"?>', '<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">' );
        foreach ($urlset as $u) {
            $u["url"] = mipurl($u["url"]);
            if (strpos($u["url"], '://')===false) {
                $u["url"] = 'https:'.$u["url"];
            }
            $xml []= implode("", array(
                "<url>",
                "<loc>", $u["url"], "</loc>",
                "<lastmod>", $u["modify"], "</lastmod>",
                "<changefreq>daily</changefreq>",
                "<priority>0.7</priority>",
                "</url>"
            ));
        }
        $xml []= '</urlset>';
        $xml = implode("\r\n", $xml);
        file_put_contents($root."sitemaps/$y/$m.xml", $xml);
    }

    public function mip_buildIndex($fileList, $domain, $root)
    {
        if (strpos($domain, '://')===false) {
            $domain = 'https:'.$domain;
        }
        $obj = array();
        foreach ($fileList as $item) {
            $obj[ $item["y"].intval($item["m"], 10) ] = implode("", array(
                "<sitemap>",
                "<loc>".$domain."sitemaps/".$item["y"]."/".$item["m"].".xml</loc>",
                "<lastmod>".date("Y-m-d")."</lastmod>",
                "</sitemap>"
            ));
        }
        $xml = file_get_contents($root."sitemaps.xml");
        $matches = array();
        $mCount = preg_match_all(
            '/<sitemap>\s*<loc>\s*http:\/\/[^\/]+\/sitemaps\/(\d+)\/(\d+)\.xml\s*<\/loc>\s*<lastmod>[^<]*<\/lastmod>\s*<\/sitemap>/i',
            $xml,
            $matches
        );
        $newXML = array(
            '<?xml version="1.0" encoding="UTF-8"?><sitemapindex xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">'
        );
        foreach ($obj as $key=>$value) {
            $newXML []= $value;
        }
        for ($i=0;$i<$mCount;$i++) {
            $key = $matches[1][$i].intval($matches[2][$i], 10);
            if (isset($obj[$key])) {
            } else {
                $newXML []= $matches[0][$i];
            }
        }
        $newXML []= '</sitemapindex>';
        $newXML = implode("\r\n", $newXML);

        file_put_contents($root."sitemaps.xml", $newXML);
    }


    /***********************************百度站内搜索通用相关模板提交索引*******************************************************/

    public function public_baidu_build()
    {
        $lastMdf['timestamp'] ='946656000';
        //读站点缓存
        $siteid = $this->siteid;
        $sitecache = getcache('sitelist', 'commons');

        //根据当前站点,取得文件存放路径
        $systemconfig = pc_base::load_config('system');
        $html_root = substr($systemconfig['html_root'], 1);
        //判断当前站点目录,是PHPCMS则把文件写到根目录下, 不是则写到分站目录下.(分站目录用由静态文件路经html_root和分站目录dirname组成)
        if ($siteid==1) {
            $dir = PHPCMS_PATH;
        } else {
            $dir = PHPCMS_PATH.$html_root.DIRECTORY_SEPARATOR.$sitecache[$siteid]['dirname'].DIRECTORY_SEPARATOR;
        }
        $page = isset($_GET['page']) && intval($_GET['page']) ? intval($_GET['page']):1;
        $pagesize=intval(trim($_GET['pagesize'])) && intval($_GET['pagesize']) ? intval($_GET['pagesize']):10;
        $offset = $pagesize*($page-1);
        //模型缓存
        // $modelcache = getcache('model','commons');

        //获取当前站点域名,下面生成URL时会用到.
        $this_domain = substr($sitecache[$siteid]['domain'], 0, strlen($sitecache[$siteid]['domain'])-1);
        $sql = implode(" ", array(
            "SELECT year(input) AS y, month(input) AS m FROM (",
            "SELECT from_unixtime(inputtime) AS input, updatetime FROM phpcms_picture WHERE status=99 AND updatetime >", $lastMdf['timestamp'],
            ") AS tab GROUP BY y, m ORDER BY MAX(updatetime) DESC limit $offset,$pagesize"
        ));

        $fileList = $this->query($sql);
        $countsql = implode(" ", array(
            "SELECT year(input) AS y, month(input) AS m FROM (",
            "SELECT from_unixtime(inputtime) AS input, updatetime FROM phpcms_picture WHERE status=99 AND updatetime >", $lastMdf['timestamp'],
            ") AS tab GROUP BY y, m ORDER BY MAX(updatetime) DESC"
        ));
        $counts = $this->query($countsql);
        $mytotal=count($counts);
        $endtotal=ceil($mytotal/$pagesize);
        if ($page<=$endtotal) {
            foreach ($fileList as $item) {
                $this->baidu_buildSitemap($item['y'], $item['m'], $dir);
            }
            $page++;
            showmessage('正在生成百度搜索索引文件第'.$page.'页/共'.$endtotal.'页', "?m=admin&c=gmap&a=public_baidu_build&page=".$page);
        }
        $this->baidu_buildIndex($counts, $this_domain, $dir);
        showmessage('百度站内搜索索引文件生成完成!继续百度合作手机baidumap地图...', "?m=admin&c=baidu_map&a=public_build");
    }

    public function baidu_buildSitemap($y, $m, $root)
    {
        $this->create_folders($root."zhannei_sitemaps/$y");
        $where = "inputtime>=".mktime(0, 0, 0, $m, 1, $y)." AND url !='' AND status=99 AND islink=0 "." AND inputtime<".mktime(0, 0, 0, ($m%12)+1, 1, $y+floor($m/12));
        $sql = array(
            "SELECT * FROM (",
            "SELECT DATE_FORMAT(FROM_UNIXTIME(updatetime),'%Y-%m-%d') AS modify,url,inputtime,thumb,title,description,keywords,updatetime,posids FROM phpcms_picture WHERE ", $where,
            ") AS tab ORDER BY modify desc"
        );
        $sql = implode(" ", $sql);
        $urlset = $this->query($sql);
        $xml = array('<?xml version="1.0" encoding="UTF-8"?>', '<urlset>' );
        foreach ($urlset as $u) {
            $u['keywords'] = $this->safeXmlString($u['keywords']);
            $keywords=str_replace(array(',',"'",'"'), ' ', $u['keywords']);
            $keywords=explode(' ', $keywords);
            $keyword='';
            if (!empty($keywords)) {
                foreach ($keywords as $k => $r) {
                    $keyword.="<tag>".$r."</tag>";
                }
                $keyword.="\r\n";
            }
            $posids=isset($u['posids']) && ($u['posids']!=0) ? '1.0' : '0.7';
            $xml []= implode("", array(
                "<url>\r\n",
                "<loc>", $u["url"], "</loc>\r\n",
                "<lastmod>", $u["modify"], "</lastmod>\r\n",
                "<changefreq>always</changefreq>\r\n",
                "<priority>",$posids,"</priority>\r\n",
                "<data>\r\n",
                "<display>\r\n",
                "<title>",$this->safeXmlString($u['title']),"</title>\r\n",
                "<content>",$this->safeXmlString($u['description']),"</content>\r\n",
                $keyword,
                "<pubTime>",date('Y-m-d', $u["updatetime"]).'T'.date('H:i:s', $u["updatetime"]),"</pubTime>\r\n",
                "<thumbnail loc=\"".$u['thumb']."\"/>\r\n",
                "<image loc=\"".$u['thumb']."\" title=\"".$this->safeXmlString($u['title'])."\"/>\r\n",
                "</display>\r\n",
                "</data>\r\n",
                "</url>\r\n"
            ));
        }
        $xml []= '</urlset>';
        $xml = implode("\r\n", $xml);
        file_put_contents($root."zhannei_sitemaps/$y/$m.xml", $xml);
    }

    public function baidu_buildIndex($fileList, $domain, $root)
    {
        $obj = array();
        foreach ($fileList as $item) {
            $obj[ $item["y"].intval($item["m"], 10) ] = implode("", array(
                "<sitemap>",
                "<loc>".$domain."/"."zhannei_sitemaps/".$item["y"]."/".$item["m"].".xml</loc>",
                "<lastmod>".date("Y-m-d")."</lastmod>",
                "</sitemap>"
            ));
        }
        //$xml = file_get_contents($root."sitemaps.xml");
        $matches = array();
        $mCount = preg_match_all(
            '/<sitemap>\s*<loc>\s*http:\/\/[^\/]+\/sitemaps\/(\d+)\/(\d+)\.xml\s*<\/loc>\s*<lastmod>[^<]*<\/lastmod>\s*<\/sitemap>/i',
            $matches
        );
        $newXML = array(
            '<?xml version="1.0" encoding="UTF-8"?><sitemapindex>'
        );
        foreach ($obj as $key=>$value) {
            $newXML []= $value;
        }
        for ($i=0;$i<$mCount;$i++) {
            $key = $matches[1][$i].intval($matches[2][$i], 10);
            if (isset($obj[$key])) {
                // $newXML []= $obj[$key];
                // unset($obj[$key]);
            } else {
                $newXML []= $matches[0][$i];
            }
        }
        //print_r( $obj );
        $newXML []= '</sitemapindex>';
        $newXML = implode("\r\n", $newXML);
        file_put_contents($root."zhannei_sitemaps.xml", $newXML);
    }

    public function safeXmlString($str)
    {
        $search  = array('<', '>', '\'', '"', '&');
        $replace = array('&lt;', '&gt;', '&apos;', '&quot;', '&amp;');
        $str=str_replace($search, $replace, $str);
        $str=preg_replace("/[\\x00-\\x08\\x0b-\\x0c\\x0e-\\x1f]/", '', $str);
        return preg_replace('/&/', '&amp;', $str);
    }
}
